/**
 * 前端登录调试工具
 * 此脚本帮助调试前端与登录API的交互问题
 */

const axios = require('axios');
const fs = require('fs');
const path = require('path');

// 颜色函数，用于控制台输出
const colors = {
  reset: "\x1b[0m",
  red: "\x1b[31m",
  green: "\x1b[32m",
  yellow: "\x1b[33m",
  blue: "\x1b[34m",
  magenta: "\x1b[35m",
  cyan: "\x1b[36m"
};

// 配置
const config = {
  apiUrl: 'https://zmyzmy.xin/api',
  username: 'admin',
  password: '123456',
  localStorageFile: path.join(__dirname, 'debug_localstorage.json'),
  outputLogFile: path.join(__dirname, 'login_debug.log'),
};

// 创建一个简单的日志记录器
const logger = {
  info: (msg, data) => {
    const logMsg = `[INFO] ${msg}${data ? ': ' + JSON.stringify(data, null, 2) : ''}`;
    console.log(`${colors.blue}${logMsg}${colors.reset}`);
    fs.appendFileSync(config.outputLogFile, `${new Date().toISOString()} ${logMsg}\n`);
  },
  success: (msg, data) => {
    const logMsg = `[SUCCESS] ${msg}${data ? ': ' + JSON.stringify(data, null, 2) : ''}`;
    console.log(`${colors.green}${logMsg}${colors.reset}`);
    fs.appendFileSync(config.outputLogFile, `${new Date().toISOString()} ${logMsg}\n`);
  },
  error: (msg, data) => {
    const logMsg = `[ERROR] ${msg}${data ? ': ' + JSON.stringify(data, null, 2) : ''}`;
    console.log(`${colors.red}${logMsg}${colors.reset}`);
    fs.appendFileSync(config.outputLogFile, `${new Date().toISOString()} ${logMsg}\n`);
  },
  warning: (msg, data) => {
    const logMsg = `[WARNING] ${msg}${data ? ': ' + JSON.stringify(data, null, 2) : ''}`;
    console.log(`${colors.yellow}${logMsg}${colors.reset}`);
    fs.appendFileSync(config.outputLogFile, `${new Date().toISOString()} ${logMsg}\n`);
  }
};

// 初始化日志文件
fs.writeFileSync(config.outputLogFile, `${new Date().toISOString()} ==== 登录调试会话开始 ====\n`);

// 模拟localStorage
const localStorage = {
  data: {},
  
  getItem(key) {
    return this.data[key] || null;
  },
  
  setItem(key, value) {
    this.data[key] = value;
    this._save();
  },
  
  removeItem(key) {
    delete this.data[key];
    this._save();
  },
  
  clear() {
    this.data = {};
    this._save();
  },
  
  _save() {
    fs.writeFileSync(config.localStorageFile, JSON.stringify(this.data, null, 2));
    logger.info('localStorage已更新', this.data);
  },
  
  _load() {
    try {
      if (fs.existsSync(config.localStorageFile)) {
        this.data = JSON.parse(fs.readFileSync(config.localStorageFile, 'utf8'));
      } else {
        this.data = {};
      }
    } catch (error) {
      logger.error('加载localStorage失败', error);
      this.data = {};
    }
  }
};

// 模拟axios实例
const api = axios.create({
  baseURL: config.apiUrl,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
});

// 请求拦截器，添加认证头
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  error => Promise.reject(error)
);

// 响应拦截器，处理错误
api.interceptors.response.use(
  response => {
    // 分析响应
    logger.info('收到响应', {
      status: response.status,
      statusText: response.statusText,
      headers: response.headers,
      data: response.data
    });
    return response.data;
  },
  error => {
    // 分析错误响应
    if (error.response) {
      logger.error('请求错误', {
        status: error.response.status,
        statusText: error.response.statusText,
        headers: error.response.headers,
        data: error.response.data
      });
    } else {
      logger.error('请求失败', {
        message: error.message,
        config: error.config
      });
    }
    return Promise.reject(error);
  }
);

// 测试登录
async function testLogin() {
  logger.info('准备测试登录', { username: config.username });
  
  try {
    logger.info('发送登录请求');
    const response = await api.post('/auth/login', {
      username: config.username,
      password: config.password
    });
    
    logger.success('登录成功');
    
    if (response.data && response.data.token) {
      // 分析token
      const token = response.data.token;
      localStorage.setItem('token', `Bearer ${token}`);
      logger.info('Token已存储到localStorage');
      
      // 解析token
      try {
        const tokenParts = token.split('.');
        if (tokenParts.length === 3) {
          const header = JSON.parse(Buffer.from(tokenParts[0], 'base64').toString());
          const payload = JSON.parse(Buffer.from(tokenParts[1], 'base64').toString());
          
          logger.info('Token解析结果', {
            header,
            payload,
            expiresAt: new Date(payload.exp * 1000).toISOString()
          });
        }
      } catch (e) {
        logger.warning('无法解析Token', e);
      }
      
      // 保存用户信息
      if (response.data.userInfo) {
        localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo));
        logger.info('用户信息已存储');
      }
    } else {
      logger.warning('响应中没有Token');
    }
    
    return true;
  } catch (error) {
    logger.error('登录失败');
    return false;
  }
}

// 测试检查API状态
async function testCheckAPIStatus() {
  try {
    logger.info('测试API状态');
    const response = await api.get('/auth/test');
    
    logger.success('API状态正常', response);
    return true;
  } catch (error) {
    logger.error('API状态检查失败');
    return false;
  }
}

// 主函数
async function main() {
  console.log('==================================================');
  console.log('     前端登录调试工具');
  console.log('==================================================');
  console.log();
  
  // 初始化localStorage
  localStorage._load();
  logger.info('已加载localStorage数据');
  
  // 清除旧的token
  localStorage.removeItem('token');
  localStorage.removeItem('userInfo');
  logger.info('已清除旧的登录状态');
  
  // 测试API状态
  await testCheckAPIStatus();
  
  // 测试登录
  const loginSuccess = await testLogin();
  
  // 如果登录成功，测试带认证的请求
  if (loginSuccess) {
    try {
      logger.info('测试带认证的请求');
      const response = await api.get('/users/current');
      logger.success('认证请求成功', response);
    } catch (error) {
      logger.error('认证请求失败');
    }
  }
  
  console.log();
  console.log('==================================================');
  console.log(`调试完成，详细日志已保存至: ${config.outputLogFile}`);
  console.log('==================================================');
}

// 执行主函数
main().catch(error => {
  logger.error('程序执行出错', error);
});
